package com.oazon.moco.playlist.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Looper;
import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.moco.launcher.fragment.PlayFragment;
import com.oazon.common.Logger;
import com.oazon.common.TaskHelper;
import com.oazon.common.util.ImageUtils;
import com.oazon.common.util.LruCacheUtil;
import com.oazon.common.util.RequestManager;
import com.oazon.common.util.StringUtils;
import com.oazon.common.util.TimeUtils;
import com.oazon.common.util.Utils;
import com.oazon.moco.playlist.PlayListManage;
import com.oazon.moco.playlist.db.ResourceDao;

/**
 * 主要做缓存工作，如缓存图片下载，并持久化数据
 * 
 * @author Gavin
 *
 */
public class RequestMediaManage {

	private static final String TAG = "RequestMediaManage";

	private static String RESOURCE_PATH = "";

	private static final int LIFE_TIME = 48 * 60 * 60 * 1000;

	private static Context context;

	private RequestQueue queue;

	private ResourceDao resourceDao;

	private static RequestMediaManage requestMediaManage = null;

	private ExecutorService fixedThreadPool;

	private RequestMediaManage() {
		resourceDao = new ResourceDao(context);
		queue = RequestManager.getRequestQueue();
		RESOURCE_PATH = context.getCacheDir().toString();
		fixedThreadPool = Executors.newFixedThreadPool(4);
	}

	public synchronized static RequestMediaManage getInstance(Context context) {

		RequestMediaManage.context = context;
		if (requestMediaManage == null) {
			requestMediaManage = new RequestMediaManage();
		}
		return requestMediaManage;
	}

	public void requsetPlayList(int size, String url,
			final AysncListener aysncListener) {
		PlayListManage.getInstance().addAll(null);
	}

	/**
	 * 判断是否是缓存在本地的歌曲
	 * 
	 * @param url
	 * @return null或者媒体的存储地址
	 */
	public String isCache(String url) {

		return resourceDao.getFilePathByUrl(url);
	}

	/**
	 * 返回的Object 是一个Bitmap 从网上下载完图片后保存在本地
	 * 
	 * @param url
	 * @param aysncListener
	 */
	public void requestBitmap(final String url,
			final AysncListener aysncListener) {

		if (aysncListener == null) {
			return;
		}

		if (StringUtils.isEmpty(url)) {
			aysncListener.onError("url is null");
			return;
		}
		String strUrltem = Utils.fixImageUrlSize(url);
		// final String strUrl = url.split("[?]")[0];

		final String strUrl = StringUtils.uriEncode(strUrltem);

		Logger.i(TAG, "request==bg" + TimeUtils.getCurrentTimeSec()
				+ "\r\n  url === " + strUrl);

		fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Bitmap result = LruCacheUtil.getInstance()
						.getBitmapFromMemCache(strUrl);
				if (result != null) {
					Logger.i(TAG, "getCcacheImageUrl=====");
					aysncListener.onSuccess(result);
					return;
				}
				String filePath = resourceDao.getFilePathByUrl(strUrl);
				if (filePath != null) {
					if (getBitmapFromSD(aysncListener, filePath) == null) {
						getBitmapFromNet(aysncListener, strUrl);
					}
				} else {
					getBitmapFromNet(aysncListener, strUrl);
				}
			}
		});

	}

	private void getBitmapFromNet(final AysncListener aysncListener,
			final String strUrl) {

		ImageRequest request = new ImageRequest(strUrl,
				new Response.Listener<Bitmap>() {

					@Override
					public void onResponse(Bitmap response) {
						if (response == null) {
							return;
						}
						// Bitmap resizeBmp = reCreatBitmap(response);
						if (aysncListener != null) {
							Logger.i(
									TAG,
									"Net===Bitmap byte==Size"
											+ response.getByteCount());
							aysncListener.onSuccess(response);
						}
						saveBitmap(strUrl, response);
					}
				}, 210, 210, Config.RGB_565, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (aysncListener != null) {
							aysncListener.onError(error.toString());
						}
					}
				});
		request.setRetryPolicy(new DefaultRetryPolicy(
				DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 0, 1.0f));
		queue.add(request);
	}

	public Bitmap getBitmapFromSD(final AysncListener aysncListener,
			String filePath) {
		try {
			Bitmap bitmap = null;

			File file = new File(filePath);
			if (file != null) {
				BitmapFactory.Options opt = new BitmapFactory.Options();
				opt.inPreferredConfig = Bitmap.Config.RGB_565;
				opt.inPurgeable = true;
				opt.inInputShareable = true;
				bitmap = BitmapFactory.decodeStream(new FileInputStream(file),
						null, opt);
			}
			Logger.i(TAG, "getBitmapFromSD=====" + bitmap.getByteCount());
			if (bitmap.getByteCount() < 1024) {
				return null;
			}
			aysncListener.onSuccess(bitmap);
			LruCacheUtil.getInstance().addBitmapToMemoryCache(
					resourceDao.getNetUrlByFilePath(filePath), bitmap);
			return bitmap;
		} catch (Exception e) {
			aysncListener.onError(e.toString());
			e.printStackTrace();
			return null;
		}
	}

	@Deprecated
	private Bitmap reCreatBitmap(Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}
		Matrix matrix = new Matrix();
		float sx = 256.0f / bitmap.getWidth();
		float sy = 256.0f / bitmap.getHeight();
		if (sx > sy)
			sx = sy;
		matrix.postScale(sx, sx);
		Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), matrix, true);

		return resizeBmp;
	}

	private void saveBitmap(final String strUrl, Bitmap reBmp) {
		if (strUrl == null || reBmp == null) {
			return;
		}
		String path = null;
		try {
			path = RESOURCE_PATH + "/" + URLEncoder.encode(strUrl, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String savePath = resourceDao.saveBitmapSD(reBmp, path);
		LruCacheUtil.getInstance().addBitmapToMemoryCache(strUrl, reBmp);
		if (savePath != null) {
			resourceDao.insertIntoResource(strUrl, savePath,
					String.valueOf(LIFE_TIME));
		}
	}
}
